package services

import (
	"errors"
	"lingc/models"
	"lingc/utils"
	"time"

	"gorm.io/gorm"
)

// AuthGroupService 提供账号登录校验的服务
type AuthGroupService struct {
	DB *gorm.DB
}

// NewAuthGroupService 创建一个新的 AuthGroupService 实例
func NewAuthGroupService(db *gorm.DB) *AuthGroupService {
	return &AuthGroupService{DB: db}
}

//表单业务

/**
 * @Description: 分页获取权限组列表
 * @param where
 * @param page
 * @param pageSize
 * @return []*models.AuthGroup
 * @return int
 * @return int64
 * @return error
 */
func (s *AuthGroupService) PageAuthGroupList(where string, page, pageSize int) ([]*models.AuthGroupList, int, int64, error) {
	var groups []*models.AuthGroup
	var total int64

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 获取总记录数
	if err := s.DB.Model(&models.AuthGroup{}).Where(where).Count(&total).Error; err != nil {
		return nil, 1, 0, err
	}

	// 获取分页数据
	if err := s.DB.Where(where).Offset(offset).Limit(pageSize).Order("id DESC").Find(&groups).Error; err != nil {
		return nil, 1, 0, err
	}
	var list []*models.AuthGroupList
	list = []*models.AuthGroupList{}
	for _, data := range groups {

		rules_ids, _ := NewAuthRuleService(utils.MysqlClient).PageAuthRuleIds(data.Rules)
		list = append(list, &models.AuthGroupList{
			ID:        data.ID,
			Title:     data.Title,
			Status:    data.Status,
			Rules:     data.Rules,
			RulesIds:  rules_ids,
			AppID:     data.AppID,
			CreatedAt: time.Unix(data.CreatedAt, 0).Format("2006-01-02 15:04:05"), // 格式化时间戳
			UpdatedAt: time.Unix(data.UpdatedAt, 0).Format("2006-01-02 15:04:05"), // 格式化时间戳
		})
	}

	return list, page, total, nil
}

/**
 * @Description: 创建新权限组
 * @param username
 * @param password
 * @param realname
 * @param avatar
 * @param status
 * @return *models.AuthGroupCreate
 * @return error
 */
func (s *AuthGroupService) CreateAuthGroup(group *models.AuthGroupCreate) (*models.AuthGroupCreate, error) {
	// 检查权限组名是否已存在
	var existingUser models.AuthGroup
	if err := s.DB.Where("title = ?", group.Title).First(&existingUser).Error; err == nil {
		return nil, errors.New("权限组名已存在")
	}
	addData := &models.AuthGroup{
		Title:     group.Title,
		Status:    group.Status,
		Rules:     group.Rules,
		CreatedAt: time.Now().Unix(),
		UpdatedAt: time.Now().Unix(),
	}
	// 保存新权限组到数据库
	if err := s.DB.Create(addData).Error; err != nil {
		return nil, err
	}
	return group, nil
}

// GetAuthGroup 获取权限组信息
func (s *AuthGroupService) GetAuthGroup(where string) (*models.AuthGroup, error) {
	var data models.AuthGroup
	if err := s.DB.Where(where).First(&data).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("权限组不存在")
		}
		return nil, err
	}
	// log.Printf("data_info:%v", data)
	return &data, nil
}

/**
 * @Description: 更新权限组信息
 * @param data
 * @return error
 */
func (s *AuthGroupService) UpdateAuthGroup(group *models.AuthGroupUpdate) (*models.AuthGroupUpdate, error) {
	// 检查权限组名是否已存在
	var existingUser models.AuthGroup
	if err := s.DB.Where("id = ?", group.ID).First(&existingUser).Error; err != nil {
		return nil, errors.New("数据不存在")
	}
	existingUser.Title = group.Title
	existingUser.Status = group.Status
	existingUser.Rules = group.Rules
	existingUser.UpdatedAt = time.Now().Unix()
	return group, s.DB.Save(existingUser).Error
}

/**
 * @Description: 删除权限组
 * @param id
 * @return error
 */
func (s *AuthGroupService) DeleteAuthGroup(id uint) error {
	var group models.AuthGroup
	if err := s.DB.Where("id = ?", id).First(&group).Error; err != nil {
		return errors.New("数据不存在")
	}
	return s.DB.Delete(&group).Error
}

/**
 * @Description: 批量删除权限组
 * @param id
 * @return error
 */
func (s *AuthGroupService) DeleteAuthGroups(ids []string) error {
	for _, id := range ids {
		var group models.AuthGroup
		if err := s.DB.Where("id = ?", id).First(&group).Error; err != nil {
			return errors.New("数据不存在")
		}
		err := s.DB.Delete(&group).Error
		if err != nil {
			return errors.New("删除失败")
		}
	}
	return nil
}
